package OrderRefundService

import (
	"context"
	"database/sql"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/tools"
	"gdshop-back-end-go/service-order/OrderService"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

func getPageListTypeToStatus(listType int) int {
	return listType
}

func Page(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	listType := r.GetInt("list_type", 0)

	fields := []string{}
	fields = append(fields, "os.*")
	fields = append(fields, "o.order_no")
	//fields = append(fields, "o.store_name")
	fields = append(fields, "o.store_id")
	fields = append(fields, "o.create_at")
	fields = append(fields, "o.recipient_name")
	fields = append(fields, "o.recipient_mobile")
	fields = append(fields, "m.realname AS buy_realname")
	fields = append(fields, "m.mobile AS buy_mobile")
	fields = append(fields, "o.remark")

	obj := toolsDb.GetUnSafaTable(ctx, "order_sub").As("os").
		LeftJoin("order o", "os.order_id = o.id").Fields(fields).
		LeftJoin("member m", "o.member_id = m.id").Where("o.delete_at < ?", 1).OrderDesc("os.id")

	if listType > 0 {
		obj.Where("os.refund_status", getPageListTypeToStatus(listType))
	} else {
		obj.Where("os.refund_status > 0")
	}

	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	count, err := obj.Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resList := res.List()
	for k, item := range resList {
		resList[k]["store_name"] = "自营"
		// 取出最后一次 order_refund
		resList[k]["refund"] = getLastOrderRefundByOrderSubId(ctx, gconv.Int(item["id"]))
	}

	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"statusTextArr":       OrderService.GetStatusTextArr(),
			"refundStatusTextArr": OrderService.GetRefundStatusTextArr(),
			"list":                resList,
			"pagination":          tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}

// 获取最后一个申请中的售后
func getLastOrderRefundByOrderSubId(ctx context.Context, orderSubId int) *entity.OrderRefund {
	var orModel *entity.OrderRefund
	err := toolsDb.GetUnSafaTable(ctx, "order_refund").Order("id DESC").
		Where("status IN (1,3,99) AND order_sub_id = ?", orderSubId).Struct(&orModel)
	if err != nil {
		return orModel
	}

	return orModel
}
